package com.example.orderconsumer.biz;

import com.example.orderconsumer.bean.OrderRequest;
import com.example.orderconsumer.service.InventoryService;
import com.example.orderconsumer.service.OrderService;
import com.example.orderconsumer.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderBizService {
    @Autowired
    private ProductService productService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private OrderService orderService;

    public String placeOrder(OrderRequest request) {
        // 1. 查询商品
        Object product = productService.findById(request.getProductId());
        if (product == null || product.toString().contains("不可用") || product.toString().contains("Not found")) {
            return "商品不存在或服务不可用";
        }
        // 2. 锁定库存
        Boolean locked = inventoryService.lockStock(request.getProductId(), request.getQuantity());
        if (locked == null || !locked) return "库存不足或服务不可用";
        // 3. 创建订单
        Integer result = orderService.createOrder(request);
        if (result != null && result > 0) return "下单成功";
        // 4. 回滚库存
        inventoryService.releaseStock(request.getProductId(), request.getQuantity());
        return "下单失败";
    }
}